import 'dart:io';

import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/color_constants.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:url_launcher/url_launcher.dart';

class VgWindowsDelegate extends UpgradeWindowsDelegate {
  final BuildContext mContext;

  static VgWindowsDelegate of() {
    return VgWindowsDelegate(AppMain.context);
  }

  VgWindowsDelegate(this.mContext);

  @override
  BuildContext get context => mContext;

  @override
  bool get whenDownloadingToDownloadWindows => true;

  @override
  Color get dialogBarrierColor => ColorConstants.BOTTOM_SHEET_BARRIER_COLOR;

  @override
  void showProgressNotification(
      {int downloadCount,
      int downloadTotal,
      FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin,
      VoidCallback defaultProcessNotification}) {
    final AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails('progress channel', 'progress channel',
            'progress channel description',
            channelShowBadge: false,
            importance: Importance.max,
            priority: Priority.high,
            onlyAlertOnce: true,
            showProgress: true,
            progress: ((downloadCount / downloadTotal) * 100)?.floor() ?? 0,
            maxProgress: 100);
    final NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidPlatformChannelSpecifics);
    flutterLocalNotificationsPlugin?.show(
        0,
        'AI前台',
        "${((downloadCount / 1024 / 1024).toStringAsFixed(2))}MB/${((downloadTotal / 1024 / 1024).toStringAsFixed(2))}MB",
        platformChannelSpecifics,
        payload: 'item x');
  }

  @override
  Widget getUpgradeWindows({
    bool isForceUpgrade,
    UpgradeInfoBean upgradeInfoBean,
    VoidCallback onConfirm,
    VoidCallback onCancel,
  }) {
    return Container(
      margin: const EdgeInsets.only(bottom: 30),
      child: _UpgradeTipsWindowsWidget(
        isForceUpgrade: isForceUpgrade,
        upgradeInfoBean: upgradeInfoBean,
        onConfirm: onConfirm,
        onCancel: onCancel,
      ),
    );
  }

  @override
  Widget getDownloadUpgradeWindows(
      {VoidCallback onPop,
      UpgradeInfoBean upgradeInfoBean,
      VoidCallback onInstallApk,
      ValueNotifier<double> progressValueNotifier,
      VoidCallback onCancelDownload}) {
    return Container(
      margin: const EdgeInsets.only(bottom: 40),
      child: _DownloadUpgradeWindowsWidget(
        onPop: onPop,
        upgradeInfoBean: upgradeInfoBean,
        onInstallApk: onInstallApk,
        onCancelDownload: onCancelDownload,
        progressValueNotifier: progressValueNotifier,
      ),
    );
  }

  @override
  Widget getWifiAutoDownloadCompleteWindows(
      {VoidCallback onInstallApk,
      VoidCallback onPop,
      UpgradeInfoBean upgradeInfoBean}) {
    return CommonConfirmCancelDialog(
      title: "提示",
      content: "Wifi环境下已为您下载好最新版本，是否立即安装？（无需消耗流量）",
      confirmText: "立即安装",
      cancelText: "暂不安装",
      onConfrim: onInstallApk,
      onPop: onPop,
      isShowLeftButton: !(upgradeInfoBean?.getPlatformForceUpgrade() ?? false),
    );
  }

  @override
  bool get dialogBarrierDismissible {
    return false;
  }
}

/// 更新提示窗口组件
///
/// @author: zengxiangxi
/// @createTime: 2/25/21 10:23 AM
/// @specialDemand:
class _UpgradeTipsWindowsWidget extends StatelessWidget {
  final bool isForceUpgrade;
  final UpgradeInfoBean upgradeInfoBean;
  final VoidCallback onConfirm;
  final VoidCallback onCancel;

  const _UpgradeTipsWindowsWidget(
      {Key key,
      this.isForceUpgrade,
      this.upgradeInfoBean,
      this.onConfirm,
      this.onCancel})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(12),
      child: Container(
        width: 300,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Stack(children: [
              //处理缝
              Positioned(
                bottom: -5,
                left: 0,
                right: 0,
                child: Container(
                  height: 10,
                  color: Colors.white,
                ),
              ),
              Image.asset("images/upgrade_top_bg.png"),
              Positioned(
                bottom: 75,
                right: 15,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      "升级新版本",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 24,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    SizedBox(height: 5),
                    Text(
                      "最新版本:${upgradeInfoBean?.versionName ?? "-"}",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 13,
                      ),
                    )
                  ],
                ),
              )
            ]),
            _toMainWidget(),
          ],
        ),
      ),
    );
  }

  Widget _toMainWidget() {
    return Container(
      decoration: BoxDecoration(color: Colors.white),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.only(top: 8, right: 16, left: 16),
            child: Text(
              "更新内容 :",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 18,
                  fontWeight: FontWeight.w600),
            ),
          ),
          Padding(
            padding:
                const EdgeInsets.only(top: 5, bottom: 5, right: 16, left: 16),
            child: Container(
              alignment: Alignment.centerLeft,
              child: Text(
                upgradeInfoBean?.updateLog ?? "",
                overflow: TextOverflow.ellipsis,
                maxLines: 10,
                style: TextStyle(
                    color: Color(0xFF333333),
                    fontSize: 15,
                    fontWeight: FontWeight.w500),
              ),
            ),
          ),
          SizedBox(height: 20),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              if(!(upgradeInfoBean?.getPlatformForceUpgrade() ?? false))
                GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () => onCancel?.call(),
                  child: Container(
                    width: 120,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border.all(
                          color: ThemeRepository.getInstance()
                              .getPrimaryColor_1890FF(),
                          width: 1),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Center(
                      child: Text(
                        "下次再说",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            color: ThemeRepository.getInstance()
                                .getPrimaryColor_1890FF(),
                            fontSize: 16,
                            height: 1.2,
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                  ),
                ),
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async {
                  if(Platform.isAndroid) {
                    String pagerUrl =
                    ConstantRepository.of().getAndroidPagerUrl();
                    if (pagerUrl != null && pagerUrl.isNotEmpty) {
                      if (await canLaunch(pagerUrl)) {
                        await launch(pagerUrl);
                      } else {
                        throw 'Could not launch $pagerUrl';
                      }
                      return;
                    }
                  }
                  onConfirm?.call();
                },
                child: Container(
                  width: 120,
                  height: 40,
                  decoration: BoxDecoration(
                    color:
                        ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Center(
                    child: Text(
                      "立即更新",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          height: 1.2,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 25),
        ],
      ),
    );
  }
}

/// 下载窗口组件
///
/// @author: zengxiangxi
/// @createTime: 2/25/21 10:23 AM
/// @specialDemand:
class _DownloadUpgradeWindowsWidget extends StatelessWidget {
  final UpgradeInfoBean upgradeInfoBean;
  final VoidCallback onPop;

  final ValueNotifier<double> progressValueNotifier;

  final VoidCallback onInstallApk;

  final VoidCallback onCancelDownload;

  const _DownloadUpgradeWindowsWidget(
      {Key key,
      this.upgradeInfoBean,
      this.onPop,
      this.progressValueNotifier,
      this.onInstallApk,
      this.onCancelDownload})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(12),
      child: Container(
        width: 300,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Stack(overflow: Overflow.visible, children: [
              //处理缝
              Positioned(
                bottom: -5,
                left: 0,
                right: 0,
                child: Container(
                  height: 10,
                  color: Colors.white,
                ),
              ),
              Image.asset("images/upgrade_top_bg.png"),
              Positioned(
                bottom: 75,
                right: 15,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      "升级新版本",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 24,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    SizedBox(height: 5),
                    Text(
                      "最新版本:${upgradeInfoBean?.versionName ?? "-"}",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 13,
                      ),
                    )
                  ],
                ),
              ),
            ]),
            _toMainWidget(),
          ],
        ),
      ),
    );
  }

  Widget _toMainWidget() {
    return Container(
      decoration: BoxDecoration(color: Colors.white),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.only(top: 8, right: 16, left: 16),
            child: Text(
              "更新内容 :",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 18,
                  fontWeight: FontWeight.w600),
            ),
          ),
          Padding(
            padding:
                const EdgeInsets.only(top: 5, bottom: 5, right: 16, left: 16),
            child: Container(
              alignment: Alignment.centerLeft,
              child: Text(
                upgradeInfoBean?.updateLog ?? "",
                overflow: TextOverflow.ellipsis,
                maxLines: 10,
                style: TextStyle(
                    color: Color(0xFF333333),
                    fontSize: 15,
                    fontWeight: FontWeight.w500),
              ),
            ),
          ),
          SizedBox(height: 20),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: ValueListenableBuilder(
              valueListenable: progressValueNotifier,
              builder: (BuildContext context, double progress, Widget child) {
                return Row(
                  children: [
                    Expanded(
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(8),
                          child: LinearProgressIndicator(
                            backgroundColor: Color(0xFF22BCFC).withOpacity(0.5),
                            value: progress ?? 0,
                            valueColor:
                                new AlwaysStoppedAnimation<Color>(Colors.blue),
                          )),
                    ),
                    Container(
                      width: 35,
                      alignment: Alignment.centerRight,
                      child: Text(
                        "${((progress ?? 0) * 100)?.floor() ?? 0}%",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            color: ThemeRepository.getInstance()
                                .getPrimaryColor_1890FF(),
                            fontSize: 12,
                            height: 1.2),
                      ),
                    )
                  ],
                );
              },
            ),
          ),
          SizedBox(height: 20),
          Center(
            child: ValueListenableBuilder(
              valueListenable: progressValueNotifier,
              builder: (BuildContext context, double progress, Widget child) {
                final bool isCompleteDownload = (progress ?? 0) >= 1;
                return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    if(!(upgradeInfoBean?.getPlatformForceUpgrade() ?? false))
                    GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        isCompleteDownload
                            ? onPop?.call()
                            : onCancelDownload?.call();
                        if (isCompleteDownload) {
                          onPop?.call();
                        } else {
                          onCancelDownload?.call();
                          onPop.call();
                        }
                      },
                      child: Container(
                        width: 120,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(
                              color: ThemeRepository.getInstance()
                                  .getPrimaryColor_1890FF(),
                              width: 1),
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Center(
                          child: Text(
                            isCompleteDownload ? "下次再说" : "取消下载",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                color: ThemeRepository.getInstance()
                                    .getPrimaryColor_1890FF(),
                                fontSize: 16,
                                height: 1.2,
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: ()  {
                        // String pagerUrl =
                        //     ConstantRepository.of().getAndroidPagerUrl();
                        // if (pagerUrl != null && pagerUrl.isNotEmpty) {
                        //   if (await canLaunch(pagerUrl)) {
                        //     await launch(pagerUrl);
                        //   } else {
                        //     throw 'Could not launch $pagerUrl';
                        //   }
                        //   return;
                        // }
                        isCompleteDownload
                            ? onInstallApk?.call()
                            : onPop?.call();
                      },
                      child: Visibility(
                        visible: (isCompleteDownload) || !(upgradeInfoBean?.isAndroidForce??false),
                        child: Container(
                          width: 120,
                          height: 40,
                          decoration: BoxDecoration(
                            color: ThemeRepository.getInstance()
                                .getPrimaryColor_1890FF(),
                            borderRadius: BorderRadius.circular(20),
                          ),
                          child: Center(
                            child: Text(
                              isCompleteDownload ? "直接安装" : "后台下载",
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16,
                                  height: 1.2,
                                  fontWeight: FontWeight.w500),
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                );
              },
            ),
          ),
          SizedBox(height: 25),
        ],
      ),
    );
  }
}
